$(function() {
	$("#message").dialog({
		autoOpen : false,
		resizable : false,
		draggable : false,
		minHeight : 0,
		show : "clip",
		hide : "clip",
		modal : true
	});

	$("#dialog").find("input").button();
});

$(document).ready(
		function() {
			$(document).on(
					"click",
					".button-send",
					function(e) {
						e.preventDefault();

						// Check white space
						if ($(this).prev().val() != "") {
							var myDate = new Date();
							var content = $(this).prev().val();
							var toUsername = "support";
							var fromUsername = "customer";
							var fromName = "Customer";

							// var displayDate = formatDate(myDate);
							var formattedDate = formatDateToServer(myDate);
							$(this).parent().prev()
									.append(
											"<strong style='font-style: italic;color: grey;'>"
													+ fromName
													+ ":</strong> " + content
													+ "</br>");

							$(this).parent().prev().animate(
									{
										scrollTop : $(this).parent().prev()
												.prop("scrollHeight")
												- $(this).parent().prev()
														.height()
									}, 0);

							$.post("http://localhost:5079/api/chat", {
								Token : token,
								ChatEvent : {
									From : fromUsername,
									FromName : fromName,
									To : toUsername,
									Time : formattedDate,
									Message : content
								}
							}, function() {
								console.log("Message was sent");
							}, "json").error(function() {
								console.log("Send message to server failed");
							});

							$(this).prev().val("");
						}
					});

			refreshtimer = setInterval(function() {
				refresh();
			}, 1000);

			initChatTabs();
			$("#chat-area").show();
			addChatTab("support", "support");
		});

function initChatTabs() {
	tabs = $("#chat-tabs").tabs({
		fx : {
			opacity : "toggle",
			duration : "fast"
		}
	});

	for ( var i = tabs.tabs('length') - 1; i >= 0; i--) {
		tabs.tabs('remove', i);
	}
}

function addChatTab(nick, name) {
	var label = name + " (" + nick + ")", id = "chat-tab-" + nick;
	if ($("#chat-tabs").find("#chat-tab-" + nick).length == 0) {
		$("#tab-navagation-panel").append(
				'<li><a href="#' + id + '">' + label + '</a></li>');
		$("#chat-tabs")
				.append(
						"<div id='"
								+ id
								+ "'><div id='chat-tab-content-"
								+ nick
								+ "' class='chat-tab-content'></div>"
								+ '<div class="input-chat-area"><input maxlength="75" class="chat-content" type="text" /><button class="button-send" type="button">Gửi</button><input class="hidden-to-username" value="'
								+ nick + '" type="hidden"/></div>' + "</div>");
		$("#chat-tabs").tabs("refresh");
		$(".button-send").button();
		$("#chat-tabs").tabs("refresh");
	}
	tabs.tabs("select", id);
	$("#chat-tab-" + nick).children().first().next().children().first().focus();
	$("#chat-tabs").find("input").button();

	$(".chat-content").keypress(
			function(e) {
				if (e.which == 13) {
					// Check white space
					if ($(this).val() != "") {
						var myDate = new Date();
						var content = $(this).val();
						var toUsername = "support";
						var fromUsername = "customer";
						var fromName = "Customer";

						// var displayDate = formatDate(myDate);
						var formattedDate = formatDateToServer(myDate);
						$(this).parent().prev().append(
								"<strong style='font-style: italic;color: grey;'>"
										+ fromName
										+ ":</strong> " + content + "</br>");
						$(this).parent().prev().animate(
								{
									scrollTop : $(this).parent().prev().prop(
											"scrollHeight")
											- $(this).parent().prev().height()
								}, 0);

						$.post("http://localhost:5079/api/chat", {
							Token : token,
							ChatEvent : {
								From : fromUsername,
								FromName : fromName,
								To : toUsername,
								Time : formattedDate,
								Message : content
							}
						}, function() {
							console.log("Message was sent");
						}, "json").error(function() {
							console.log("Send message to server failed");
						});

						$(this).val("");
					}
				}
			});
}

function refresh() {
	$.getJSON(
			"http://localhost:5079/api/chat",
			{
				Token : token
			},
			function(data) {
				$.each(data, function(index, value) {
					// var time = new Date(data[index]["Time"]);
					// var formattedDate = formatDate(time);
					var from = data[index]["From"];
					var fromname = data[index]["FromName"];
					var message = data[index]["Message"];

					addChatTab(from, fromname);
					var buttonSend = tabs.find("#chat-tab-" + from).find(
							".button-send");
					buttonSend.parent().prev().append(
							"<strong style='font-style: italic;color: darkCyan;'>"
									+ fromname + ":</strong> " + message
									+ "</br>");
					buttonSend.parent().prev().animate(
							{
								scrollTop : buttonSend.parent().prev().prop(
										"scrollHeight")
										- buttonSend.parent().prev().height()
							}, 0);
				});
			}).error(function(jqXHR, textStatus) {
		console.log("Refresh failed");
	});
}

function showMessage(content) {
	$("#message").find("#message-content").text(content);
	$("#message").dialog("open");
}

/* UTILITY */
function encrypt(content) {
	return btoa(content);
}

function formatDate(date) {
	return date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
			+ " - " + (date.getDate()) + '/' + (date.getMonth() + 1) + '/'
			+ date.getFullYear();
}

function formatDateToServer(date) {
	return date.getFullYear() + '-' + (date.getMonth() + 1) + '-'
			+ (date.getDate()) + ' ' + date.getHours() + ':'
			+ date.getMinutes() + ':' + date.getSeconds();
}

/* End UTILITY */

